package com.steve.combat.thread.多线程交替打印ABC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: STEVE
 * @Description: 多线程交替打印ABC
 * @since: 2025-06-01
 */
public class SyncPrinter implements Runnable {

    private final int PRINT_COUNT = 10;
    private final ReentrantLock reentrantLock;
    private final Condition thisCondition;
    private final Condition nextConditon;
    private final char printChar;

    public SyncPrinter(ReentrantLock reentrantLock, Condition thisCondition, Condition nextConditon, char printChar) {
        this.reentrantLock = reentrantLock;
        this.thisCondition = thisCondition;
        this.nextConditon = nextConditon;
        this.printChar = printChar;
    }

    @Override
    public void run() {
        reentrantLock.lock();
        try {
            for (int i = 0; i < PRINT_COUNT; i++) {
                System.out.print(printChar);
                nextConditon.signal();
                if (i < PRINT_COUNT - 1) {
                    try {
                        thisCondition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        } finally {
            reentrantLock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();

        Condition conditionA = lock.newCondition();
        Condition conditionB = lock.newCondition();
        Condition conditionC = lock.newCondition();

        Thread printA = new Thread(new SyncPrinter(lock, conditionA, conditionB, 'A'));
        Thread printB = new Thread(new SyncPrinter(lock, conditionB, conditionC, 'B'));
        Thread printC = new Thread(new SyncPrinter(lock, conditionC, conditionA, 'C'));

        printA.start();
        Thread.sleep(100);
        printB.start();
        Thread.sleep(100);
        printC.start();
        Thread.sleep(100);
    }

}
